// 单位转换配置
const CONVERSION_UNITS = {
  length: {
    name: '长度',
    units: {
      mm: { name: '毫米', ratio: 1 },
      cm: { name: '厘米', ratio: 10 },
      m: { name: '米', ratio: 1000 },
      km: { name: '千米', ratio: 1000000 },
      inch: { name: '英寸', ratio: 25.4 },
      ft: { name: '英尺', ratio: 304.8 },
      yard: { name: '码', ratio: 914.4 },
      mile: { name: '英里', ratio: 1609344 },
      nm: { name: '纳米', ratio: 0.000001 },
      μm: { name: '微米', ratio: 0.001 },
      dm: { name: '分米', ratio: 100 },
      hm: { name: '百米', ratio: 100000 },
      ly: { name: '光年', ratio: 9.461e18 }
    }
  },
  weight: {
    name: '重量',
    units: {
      mg: { name: '毫克', ratio: 1 },
      g: { name: '克', ratio: 1000 },
      kg: { name: '千克', ratio: 1000000 },
      ton: { name: '吨', ratio: 1000000000 },
      oz: { name: '盎司', ratio: 28349.5 },
      lb: { name: '磅', ratio: 453592 },
      stone: { name: '英石', ratio: 6350293 },
      carat: { name: '克拉', ratio: 200 },
      grain: { name: '格令', ratio: 64.79891 }
    }
  },
  temperature: {
    name: '温度',
    convert: {
      celsius: {
        name: '摄氏度',
        toFahrenheit: (c) => c * 9/5 + 32,
        toKelvin: (c) => c + 273.15
      },
      fahrenheit: {
        name: '华氏度',
        toCelsius: (f) => (f - 32) * 5/9,
        toKelvin: (f) => (f - 32) * 5/9 + 273.15
      },
      kelvin: {
        name: '开尔文',
        toCelsius: (k) => k - 273.15,
        toFahrenheit: (k) => (k - 273.15) * 9/5 + 32
      }
    }
  },
  area: {
    name: '面积',
    units: {
      mm2: { name: '平方毫米', ratio: 1 },
      cm2: { name: '平方厘米', ratio: 100 },
      m2: { name: '平方米', ratio: 1000000 },
      km2: { name: '平方千米', ratio: 1000000000000 },
      ha: { name: '公顷', ratio: 10000000000 },
      acre: { name: '英亩', ratio: 4046856422.4 },
      sqft: { name: '平方英尺', ratio: 92903.04 },
      sqin: { name: '平方英寸', ratio: 645.16 },
      sqyd: { name: '平方码', ratio: 836127.36 }
    }
  },
  volume: {
    name: '体积',
    units: {
      ml: { name: '毫升', ratio: 1 },
      l: { name: '升', ratio: 1000 },
      m3: { name: '立方米', ratio: 1000000 },
      cm3: { name: '立方厘米', ratio: 1 },
      mm3: { name: '立方毫米', ratio: 0.001 },
      gal: { name: '加仑(美)', ratio: 3785.41 },
      qt: { name: '夸脱', ratio: 946.353 },
      pt: { name: '品脱', ratio: 473.176 },
      cup: { name: '杯', ratio: 236.588 },
      floz: { name: '液体盎司', ratio: 29.5735 },
      tbsp: { name: '汤匙', ratio: 14.7868 },
      tsp: { name: '茶匙', ratio: 4.92892 }
    }
  },
  speed: {
    name: '速度',
    units: {
      mps: { name: '米/秒', ratio: 1 },
      kmh: { name: '千米/时', ratio: 0.277778 },
      mph: { name: '英里/时', ratio: 0.44704 },
      fps: { name: '英尺/秒', ratio: 0.3048 },
      knot: { name: '节', ratio: 0.514444 },
      mach: { name: '马赫', ratio: 343 }
    }
  },
  time: {
    name: '时间',
    units: {
      ms: { name: '毫秒', ratio: 1 },
      s: { name: '秒', ratio: 1000 },
      min: { name: '分钟', ratio: 60000 },
      h: { name: '小时', ratio: 3600000 },
      day: { name: '天', ratio: 86400000 },
      week: { name: '周', ratio: 604800000 },
      month: { name: '月', ratio: 2629746000 },
      year: { name: '年', ratio: 31556952000 }
    }
  }
};

// 单位转换器类
class UnitConverter {
  constructor() {
    this.units = CONVERSION_UNITS;
  }

  // 通用单位转换（基于比例）
  convertUnit(value, fromUnit, toUnit, category) {
    const units = this.units[category]?.units;
    if (!units || !units[fromUnit] || !units[toUnit]) {
      throw new Error(`不支持的单位转换: ${fromUnit} -> ${toUnit}`);
    }
    
    // 转换为基础单位，再转换为目标单位
    const baseValue = value * units[fromUnit].ratio;
    return baseValue / units[toUnit].ratio;
  }

  // 温度转换（特殊处理）
  convertTemperature(value, fromUnit, toUnit) {
    const converters = this.units.temperature.convert;
    
    if (fromUnit === toUnit) return value;
    
    // 直接转换
    if (fromUnit === 'celsius') {
      if (toUnit === 'fahrenheit') return converters.celsius.toFahrenheit(value);
      if (toUnit === 'kelvin') return converters.celsius.toKelvin(value);
    }
    
    if (fromUnit === 'fahrenheit') {
      if (toUnit === 'celsius') return converters.fahrenheit.toCelsius(value);
      if (toUnit === 'kelvin') return converters.fahrenheit.toKelvin(value);
    }
    
    if (fromUnit === 'kelvin') {
      if (toUnit === 'celsius') return converters.kelvin.toCelsius(value);
      if (toUnit === 'fahrenheit') return converters.kelvin.toFahrenheit(value);
    }
    
    throw new Error(`不支持的温度转换: ${fromUnit} -> ${toUnit}`);
  }

  // 获取类别的所有单位
  getUnitsForCategory(category) {
    const categoryData = this.units[category];
    if (!categoryData) {
      throw new Error(`不支持的类别: ${category}`);
    }
    
    if (category === 'temperature') {
      return Object.keys(categoryData.convert).map(key => ({
        key,
        name: categoryData.convert[key].name
      }));
    }
    
    return Object.keys(categoryData.units).map(key => ({
      key,
      name: categoryData.units[key].name
    }));
  }

  // 获取所有支持的类别
  getAllCategories() {
    return Object.keys(this.units).map(key => ({
      key,
      name: this.units[key].name
    }));
  }

  // 验证转换是否支持
  isConversionSupported(fromUnit, toUnit, category) {
    try {
      if (category === 'temperature') {
        const converters = this.units.temperature.convert;
        return converters[fromUnit] && converters[toUnit];
      } else {
        const units = this.units[category]?.units;
        return units && units[fromUnit] && units[toUnit];
      }
    } catch (error) {
      return false;
    }
  }

  // 获取单位的显示名称
  getUnitDisplayName(unit, category) {
    if (category === 'temperature') {
      return this.units.temperature.convert[unit]?.name || unit;
    } else {
      return this.units[category]?.units[unit]?.name || unit;
    }
  }

  // 批量转换
  batchConvert(value, fromUnit, category, targetUnits = []) {
    const results = [];
    
    if (targetUnits.length === 0) {
      // 如果没有指定目标单位，转换为该类别的所有单位
      targetUnits = this.getUnitsForCategory(category).map(u => u.key);
    }
    
    targetUnits.forEach(toUnit => {
      try {
        let convertedValue;
        if (category === 'temperature') {
          convertedValue = this.convertTemperature(value, fromUnit, toUnit);
        } else {
          convertedValue = this.convertUnit(value, fromUnit, toUnit, category);
        }
        
        results.push({
          unit: toUnit,
          value: convertedValue,
          displayName: this.getUnitDisplayName(toUnit, category)
        });
      } catch (error) {
        console.warn(`转换失败: ${fromUnit} -> ${toUnit}`, error);
      }
    });
    
    return results;
  }

  // 智能转换建议
  getSuggestedConversions(value, unit, category) {
    const suggestions = [];
    
    // 根据数值大小推荐合适的单位
    if (category === 'length') {
      if (unit === 'm') {
        if (value >= 1000) suggestions.push('km');
        if (value <= 0.01) suggestions.push('cm');
        if (value <= 0.0001) suggestions.push('mm');
      }
    } else if (category === 'weight') {
      if (unit === 'g') {
        if (value >= 1000) suggestions.push('kg');
        if (value >= 1000000) suggestions.push('ton');
        if (value <= 0.001) suggestions.push('mg');
      }
    }
    
    return suggestions;
  }
}

module.exports = { UnitConverter, CONVERSION_UNITS };